<?php
class SystemPreferencesController extends AppController {
    var $name = 'SystemPreferences';

    var $pageTitle = 'System Preferences';

    var $viewPath = 'its/admins/system_preferences';

    var $uses = array('SystemPreference');


    function beforeFilter() {
        parent::beforeFilter();
        $this->set('parentNav', 'its_admins');
        $this->Auth->allowedActions = array('*');
        $this->set('tabMenu', 'tabmenus/its/admins');
    }

    function display() {
        $config = $this->SystemPreference->find('list', array('fields' => array('name', 'value')));
        $this->set('config', $config);
    }

    function get($name, $field = 'value') {
        $var = $this->SystemPreference->findByName($name);
        if ($var != null) {
            return $var['SystemPreference'][$field];
        } else {
            return null;
        }
    }

    function save() {
        $is_success = true;
        $this->SystemPreference->query("BEGIN");;
        foreach($this->data as $name => $value) {
            // CakePHP ต้อง Save (update) โดยดูจาก primary key (id) เท่านั้น
            $id = $this->get($name, 'id');
            // ถ้าเป็น config ค่าใหม่
            if ($id == null) {
                $data['SystemPreference']['id'] = null;
                $data['SystemPreference']['name'] = $name;
                $data['SystemPreference']['value'] = $value;
                $this->SystemPreference->save($data);
            } else {
                $this->SystemPreference->id = $id;
                $is_success &= $this->SystemPreference->saveField('value', $value);
            }
            if (!$is_success) break;
        }

        if ($is_success) {
            $this->SystemPreference->query("COMMIT");;
            $this->Session->setFlash("Save succesfull.", 'flash/ok');
        } else {
            $this->SystemPreference->query("ROLLBACK");
            $this->Session->setFlash("Save fail!!!.", 'flash/fail');
        }
        $this->setAction('display');
    }
}
?>
